# -*- coding: utf-8 -*-
from __future__ import absolute_import

"""
可视化脚本
以月的云量统计数据为输入数据
1 给出该月每一天的云量地图
2 给出该月每个县的逐天变化曲线
"""
import glob
import pandas as pd
import os
import seaborn
seaborn.set_style("darkgrid", {"font.sans-serif": ['simhei', 'Arial']})

import re
import matplotlib.pyplot as plt

import geopandas
import geoplot

def get_month_avrg(statistics):
    files = []
    files.extend(glob.glob("{}\\*逐年平均结果.csv".format(statistics)))

    # 按照月份阿拉伯数字来给文件排序，
    # 在python2中用法为 files.sort(key=lambda f: int(filter(str.isdigit, f)))
    files.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))
    month_avrgs = pd.DataFrame()
    loc_n = 2
    for file in files:
        month_matrix = pd.read_csv(file, engine='python')
        if loc_n == 2:
            month_avrgs.insert(loc=0, value=month_matrix['县市'], column='县市')
            month_avrgs.insert(loc=1, value=month_matrix['邮编'], column='邮编')
        col_list = list(month_matrix)
        col_list.remove('Unnamed: 0')
        col_list.remove('Unnamed: 0.1')
        col_list.remove('县市')
        col_list.remove('邮编')
        col_list.remove('月均')
        avg_col = re.findall('(\d+)', os.path.split(file)[1])[0]
        month_matrix[avg_col] = (month_matrix[col_list].sum(axis=1)) / len(col_list)
        month_avrgs.insert(value=month_matrix[avg_col], column=avg_col, loc=loc_n)
        loc_n = loc_n + 1
    return month_avrgs

def plot_month_map(statistics, shp):
    shp_df = geopandas.read_file(shp)
    print(shp_df.head())
    month_avrgs_df = get_month_avrg(statistics)
    print()
    month_avrgs_df = month_avrgs_df.rename(columns={'邮编': 'PAC'})
    merged_df = shp_df.merge(month_avrgs_df, on='PAC')
    hue_list = list(month_avrgs_df)
    hue_list.remove('PAC')
    hue_list.remove('县市')
    poly_kwargs = {'linewidth': 1.5, 'edgecolor': 'black', 'zorder': -1}
    # point_kwargs = {'linewidth': 0.5, 'edgecolor': 'black', 'alpha': 1}
    legend_kwargs = {'frameon': True}
    for hue in hue_list:
        ax = geoplot.polyplot(merged_df, **poly_kwargs)
        # geoplot.choropleth(merged_df, hue=hue, legend=True, cmap='copper_r')
        geoplot.cartogram(merged_df, scale=hue, ax=ax, hue=hue, cmap='winter_r',
                          trace=False,
                          legend=True, legend_var='scale',
                          legend_values=[2, 0.8, 0.5],
                          legend_labels=['云量极多', '云量很多', '云量较少'],
                          legend_kwargs=legend_kwargs)
        plt.title('{}月全岛云量县市差异示意地图'.format(hue))
        plt.savefig('{}月全岛云量空间差异分布情况'.format(hue))
        # plt.show()
        # break
    pass


def plot_county_year(statistics):
    month_avrgs = get_month_avrg(statistics)

    COL = month_avrgs['县市'].tolist()

    col_list = list(month_avrgs)
    col_list.remove('县市')
    col_list.remove('邮编')
    DATA = month_avrgs[col_list].T
    DATA.index = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    DATA.columns = COL
    # plt.show()
    north_countys = ['琼山区', '美兰区', '文昌市', '秀英区', '澄迈县', '龙华区']
    east_countys = ['琼海市', '万宁市']
    west_countys = ['临高县', '儋州市', '白沙黎族自治县', '昌江黎族自治县', '东方市']
    center_countys = ['定安县', '五指山市', '屯昌县', '琼中黎族苗族自治县']
    sourth_countys = ['保亭黎族苗族自治县', '乐东黎族自治县', '陵水黎族自治县', '天涯区', '吉阳区', '海棠区', '崖州区']
    seaborn.lineplot(data=DATA[west_countys], linewidth=2, sort=False, legend='full', dashes=False).set_title("西部沿海地区月际云量差异")

    plt.show()


if __name__ == "__main__":
    shp = "F:\\data\\modis_terra_cloud_mask\\shapefile\\hainan_24_county.shp"
    plot_month_map("P:\\CG_CODE\\modis\\data\\cloud", shp)